
#if !defined(_KERNEL) && !defined(_STANDALONE)
#include <limits.h>
#include <stdint.h>
#include <strings.h>
#else
#include <lib/libkern/libkern.h>
#include <machine/limits.h>
#endif

#ifndef popcount64	// might be defined to use a __builtin

/*
 * If uint64_t is larger than size_t, the follow assumes that
 * splitting into 32bit halves is faster.
 *
 * The native pocount64 version is based on the same ideas as popcount32(3),
 * see popcount32.c for comments.
 */

#if SIZE_MAX < 0xffffffffffffffffULL
unsigned int
popcount64(uint64_t v)
{
	return popcount32((uint32_t)(v >> 32)) +
	    popcount32((uint32_t)(v & 0xffffffffULL));
}
#else
unsigned int
popcount64(uint64_t v)
{
	unsigned int c;

	v = v - ((v >> 1) & (uint64_t)0x5555555555555555ULL);
	v = (v & (uint64_t)0x3333333333333333ULL) +
	    ((v >> 2) & (uint64_t)0x3333333333333333ULL);
	v = ((v + (v >> 4)) & (uint64_t)0x0f0f0f0f0f0f0f0fULL) *
	    (uint64_t)0x0101010101010101ULL;
	c = (unsigned int)(v >> 56);

	return c;
}
#endif

#if ULONG_MAX == 0xffffffffffffffffULL
__strong_alias(popcountl, popcount64)
#endif

#if ULLONG_MAX == 0xffffffffffffffffULL
__strong_alias(popcountll, popcount64)
#endif

#if defined(__alioth)
__strong_alias(popcountti2, popcount64)
#endif /* defined(__alioth) */

#endif /* !popcount64 */
